package group9;

import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Claudio Herreros, Dylan James, Tyler Berg
 *
 */

@SuppressWarnings("serial")
public class SignInServlet extends HttpServlet {

	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		String userName = req.getParameter("UserName");
		String password = req.getParameter("Password");
		
		String encryptedPassword;
		try{
			MessageDigest crypt = MessageDigest.getInstance("MD5");
			crypt.update(password.getBytes(), 0, password.length());
			encryptedPassword = new BigInteger(1, crypt.digest()).toString(16);
		}catch(NoSuchAlgorithmException ie){
			
			req.setAttribute("errorMessage", "Encryption Error");
			RequestDispatcher rd = req.getRequestDispatcher("login.jsp");
			try {
				rd.forward(req, resp);
			} catch (ServletException e) {
				e.printStackTrace();
			}
			return;
		}
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		Query userQuery = pm.newQuery("select from " + User.class.getName());
		userQuery.setFilter("userName == '" + userName + "'");
		
		List<User> results = (List<User>) userQuery.execute();
		
		if (results.size() == 1)
		{
			User user = results.get(0);
			
			if (user.checkPassword(encryptedPassword))
			{
				req.getSession().setAttribute("User", user);
				resp.sendRedirect("home.jsp");
				return;
			}
			else
			{
				req.setAttribute("errorMessage", "Incorrect Password");
				RequestDispatcher rd = req.getRequestDispatcher("login.jsp");
				try {
					rd.forward(req, resp);
				} catch (ServletException e) {
					e.printStackTrace();
				}
				return;
			}
		}
		
		if (results.size() == 0)
		{
			req.setAttribute("errorMessage", "User Name not found");
			RequestDispatcher rd = req.getRequestDispatcher("login.jsp");
			try {
				rd.forward(req, resp);
			} catch (ServletException e) {
				e.printStackTrace();
			}
			return;
		}
		
		req.setAttribute("errorMessage", "Multiple users found with username: " + userName);
		RequestDispatcher rd = req.getRequestDispatcher("login.jsp");
		try {
			rd.forward(req, resp);
		} catch (ServletException e) {
			e.printStackTrace();
		}
		return;
		
	}
}
